{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# Asynchronous output\n",
        "\n",
        "Javascript and Node.JS make heavy use of asynchronous execution. IJavascript lets you exercise these asynchronous capabilities, both:\n",
        "\n",
        "- by updating `stdout` and `stderr` asynchronously, or\n",
        "- by providing an execution result asynchronously."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Synchronous *vs* asynchronous code\n",
        "\n",
        "In simple words, this tutorial use the term \"asynchronous code\" to refer to code that doesn't run immediately (code in callback functions). For example, this is asynchronous code:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Hello, World!\n"
          ]
        }
      ],
      "source": [
        "function sayHello() {\n",
        "    console.log(\"Hello, World!\");\n",
        "}\n",
        "var t = setTimeout(sayHello, 1000);"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "whereas this is not:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 2,
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Hello, World!\n"
          ]
        }
      ],
      "source": [
        "function sayHello() {\n",
        "    console.log(\"Hello, World!\");\n",
        "}\n",
        "sayHello();"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## `$$.async()`\n",
        "\n",
        "By default, IJavascript assumes an execution request is synchronous code. That is, IJavascript will evaluate the execution request, return the result and advertise that is ready to receive more requests. \n",
        "\n",
        "If an execution request invokes the function `$$.async()`, IJavascript will treat the execution request as asynchronous code. Unlike synchronous code, asynchronous code should return a result by invoking `$$.sendResult(result)` or `$$.sendError(error)`. Or alternatively, invoke `$$.done()` to indicate that no result will be returned. For example:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 3,
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Hello, World!\n"
          ]
        }
      ],
      "source": [
        "$$.async();\n",
        "\n",
        "console.log(\"Hello, World!\");\n",
        "\n",
        "setTimeout($$.done, 1000);"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Accessing the global object `$$` from asynchronous code\n",
        "\n",
        "Asynchronous code should make a copy of the global object `$$`, to ensure a result is returned to the appropriate cell. There are several patterns to make this copy, each with their own pros and cons:\n",
        "\n",
        "- using a variable to store a copy the `$$` linked to the asynchronous cell,\n",
        "\n",
        "- using a function environment,\n",
        "\n",
        "- or using a block-scoped `let` (requires ES6)."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### Using a variable to store a copy of the `$$` linked to an asynchronous cell\n",
        "\n",
        "The main drawback of this pattern is that it requires a new variable per asynchronous cell. See example:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 4,
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Hello, world!\n"
          ]
        },
        {
          "data": {
            "text/plain": [
              "'Bye!'"
            ]
          },
          "execution_count": 4,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "$$.async();\n",
        "\n",
        "var cell1 = {\n",
        "    $$: $$,\n",
        "    console: console,\n",
        "};\n",
        "\n",
        "setTimeout(function() {\n",
        "    cell1.console.log(\"Hello, world!\");\n",
        "    cell1.$$.sendResult(\"Bye!\");\n",
        "}, 1000);"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### Using a function environment\n",
        "\n",
        "A function environment lets you create a copy of a global variable into a local variable with the same name (and thus, it doesn't require the creation of a new variable name for every asynchronous cell). See the example below:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 5,
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Hello, world!\n"
          ]
        },
        {
          "data": {
            "text/plain": [
              "'Bye!'"
            ]
          },
          "execution_count": 5,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "$$.async();\n",
        "\n",
        "(function($$, console) {\n",
        "    setTimeout(function() {\n",
        "        console.log(\"Hello, world!\");\n",
        "        $$.sendResult(\"Bye!\");\n",
        "    }, 1000);\n",
        "})($$, console);"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### Using a block-scoped `let` (requires ES6)\n",
        "\n",
        "If the version of Node.js in your system supports ES6, you can use `let` to define local variables in a block scope that contains the asynchronous code:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 6,
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Hello, world!\n"
          ]
        },
        {
          "data": {
            "text/plain": [
              "'Bye!'"
            ]
          },
          "execution_count": 6,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "\"use strict\";\n",
        "\n",
        "$$.async();\n",
        "\n",
        "{\n",
        "    let console = global.console;\n",
        "    let $$ = global.$$;\n",
        "\n",
        "    setTimeout(function() {\n",
        "        console.log(\"Hello, world!\");\n",
        "        $$.sendResult(\"Bye!\");\n",
        "    }, 1000);\n",
        "}"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Javascript (Node.js)",
      "language": "javascript",
      "name": "javascript"
    },
    "language_info": {
      "file_extension": ".js",
      "mimetype": "application/javascript",
      "name": "javascript",
      "version": "10.21.0"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 1
}
